<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>canvas 统计图</title>
  <style>
    body {
      text-align: center;
    }

    #canvas {
      background-color: #cccccc;
    }
  </style>
</head>

<body>
  <h3>绘制销售统计图</h3>
  <canvas id="canvas" width="500" height="400"></canvas>

  <script>
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");

    var list = [
      {name: "北口",value: 1000 },
      {name: "南口",value: 1200 },
      {name: "地铁口",value: 2000 },
      {name: "交叉口",value: 1300 },
    ];
    var colors =  ['#c23531','#2f4554', '#61a0a8', '#d48265', '#91c7ae','#749f83', '#ca8622', '#bda29a','#6e7074', '#546570',
          '#c4ccd3'];

    for (let i = 0; i < list.length; i++) {
      var width = 50;
      var height = list[i].value / 10;
      var x = 100 * i + 50;
      var h = 400 - height;

      // 设置随机颜色
      // ctx.globalAlpha = 0.5; // 透明度
      // ctx.fillStyle = random_color();
      var idx = Math.floor(Math.random()*colors.length);
      ctx.fillStyle = colors[idx];
      // 绘制矩形
      ctx.fillRect(x, h, width, height);
      // 名称
      var name = list[i].name;
      var txtX = x;
      var txtY = h - 20;
      ctx.fillStyle = "#000"
      ctx.font = "20px SimHei"
      ctx.fillText(name, txtX, txtY);
    }

    function random_color() {
      var r = Math.floor(Math.random() * 256);
      var g = Math.floor(Math.random() * 256);
      var b = Math.floor(Math.random() * 256);
      return `rgb(${r},${g},${b})`;
    }
  </script>
</body>

</html>